// 练习 4.1: 编写一个函数，计算两个SHA256哈希码中不同bit的数目。(参考2.6.2节的 PopCount函数。)
package main

import (
	"crypto/sha256"
	"fmt"
)

var pc [256]byte

func init() {
	for i := range pc {
		pc[i] = pc[i/2] + byte(i&1)
	}
}

func main() {
	a := sha256.Sum256([]byte("x"))
	b := sha256.Sum256([]byte("X"))
	bits := diffBits(a, b)
	fmt.Printf("%b\n%b\n%t\n%d\n", a, b, a == b, bits)
}

func diffBits(a, b [32]byte) int {
	var bits int
	for i := 0; i < 32; i++ {
		byte := a[i] ^ b[i]
		bits += int(pc[byte])
	}
	return bits
}
